﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.Services;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.IO;
using System.Xml;
using System.Runtime.Serialization.Formatters.Binary;

namespace MLY.LTR
{
  public partial class WoDownload : Bll.BasePage
  {
    bool isClient { get { return isClientHidden.Value != "" ? true : false; } }

    protected void Page_Load(object sender, EventArgs e)
    {
      currId = -1;
      if (!this.IsPostBack)
      {
        if (Request.ServerVariables["HTTP_REFERER"] != null)
          ViewState["Referer"] = Request.ServerVariables["HTTP_REFERER"];
        else
          ViewState["Referer"] = this.Request.Url.ToString();

        RadioButton1.Checked = true;
        fromToPanel.Enabled = false;
        fromPanel.Enabled = true;
        if (Request.QueryString["isclient"] != null)
          isClientHidden.Value = "true";
        else
          isClientHidden.Value = "";
        setOrgDdl();
      }
      else
      {
        if (RadioButton1.Checked == false && RadioButton2.Checked == false)
        {
          RadioButton1.Checked = true;
          RadioButton2.Checked = false;
          fromToPanel.Enabled = false;
          fromPanel.Enabled = true;
        }
        else
        {
          if (RadioButton1.Checked == true && RadioButton2.Checked == true)
          {
            if (fromPanel.Enabled)
            {
              fromPanel.Enabled = false;
              fromToPanel.Enabled = true;
              RadioButton1.Checked = false;
            }
            else
            {
              fromPanel.Enabled = true;
              fromToPanel.Enabled = false;
              RadioButton2.Checked = false;
            }
          }
        }
      }
      errBox.Text = "";
    }

    int currId;

    void setOrgDdl()
    {
      if (isClientHidden.Value != "")
      {
        ContractorIdDdl.DataSource = Bll.clsOrganization.GetContractorsByClientId(SessParam.OrganizationId);
      }
      else
      {
        ContractorIdDdl.DataSource = Bll.clsOrganization.GetClientsByContractorId(SessParam.OrganizationId);
      }
      ContractorIdDdl.DataBind();
    }

    protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
    {
      if (RadioButton2.Checked)
      {
        RadioButton1.Checked = false;
        fromToPanel.Enabled = true;
        fromPanel.Enabled = false;
      }
    }

    protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
    {
      if (RadioButton1.Checked)
      {
        RadioButton2.Checked = false;
        fromToPanel.Enabled = false;
        fromPanel.Enabled = true;
      }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
      Response.RedirectTo(ViewState["Referer"].ToString());
    }

    protected void btnOk_Click(object sender, ImageClickEventArgs e)
    {
    }

    void sendFile()
    {
      if (currId != 0)
      {
        string where = "";
        if (isClientHidden.Value == "")
          where = String.Format(" CustomerId = {1} AND ContractorId = {0} ", SessParam.OrganizationId, ContractorIdDdl.SelectedValue);
        else
          where = String.Format(" CustomerId = {0} AND ContractorId = {1} ", SessParam.OrganizationId, ContractorIdDdl.SelectedValue);
        if (RadioButton1.Checked)
        {
          if (fromDateBox.Text != "")
            //where += String.Format(" AND SendDate > '{0}' ", DateTime.Parse(fromDateBox.Text).ToString("MM/dd/yyyy"));
            where += String.Format(" AND SendDate >= {0} ", Utils.FormatDateToSql(DateTime.Parse(fromDateBox.Text)));
        }
        else
        {
          if (FromDateBoxes.Text != "")
            //where += String.Format(" AND SendDate > '{0}' ", DateTime.Parse(FromDateBoxes.Text).ToString("MM/dd/yyyy"));
            where += String.Format(" AND SendDate >= {0} ", Utils.FormatDateToSql(DateTime.Parse(FromDateBoxes.Text)));
          if (ToDateBoxes.Text != "")
            //where += string.Format(" AND SendDate < '{0}' ", DateTime.Parse(ToDateBoxes.Text).ToString("MM/dd/yyyy"));
            where += string.Format(" AND SendDate <= {0} ", Utils.FormatDateToSql(DateTime.Parse(ToDateBoxes.Text)));
        }

        string fileName = "";
        List<Dal.TableWorkOrder> dealsToAdd = Bll.clsWorkOrder.getDataFromWhere(where, "");
        if (dealsToAdd.Count == 0)
        {
          showErr("No Deals To Display!", new Exception(), false);
          return;
        }
        MemoryStream liveStream = null;

        if (formatDdl.SelectedValue.ToLower() == "xml")
        {
          liveStream = getXmlstream(dealsToAdd);
          fileName = String.Format("workOrders{0}_{1}.xml",
              DateTime.Now.ToShortDateString().Replace(@"\", "_").Replace(@"/", "_"),
              DateTime.Now.ToShortTimeString().Replace(@"\", "_").Replace(@"/", "_"));

        }
        else
        {
          liveStream = getCsvstream(dealsToAdd);
          fileName = String.Format("workOrders{0}_{1}.csv",
              DateTime.Now.ToShortDateString().Replace(@"\", "_").Replace(@"/", "_"),
              DateTime.Now.ToShortTimeString().Replace(@"\", "_").Replace(@"/", "_").Replace(":", "_"));
        }

        liveStream.Position = 0;
        BinaryFormatter bf = new BinaryFormatter();
        string o = (string)bf.Deserialize(liveStream);
        liveStream.Close();

        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

        byte[] buffer = new byte[(int)enc.GetBytes(o).Length];
        buffer = enc.GetBytes(o);

        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Length", buffer.Length.ToString());
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.BinaryWrite(buffer);
        Response.End();

      }

    }

    void showErr(string msg, Exception ex, bool isError)
    {
      errBox.Text = msg;
      errBox.Visible = true;
      Bll.tblLogger.AddLogEntry(string.Format("Error {0} : {1}", msg, ex.Message), isError);
    }

    XmlElement getElement(string name, XmlDocument doc, object val)
    {
      XmlElement retval = doc.CreateElement(name);
      if (val != null)
        retval.InnerText = val.ToString();
      return retval;
    }

    public string formatStringToCsv(string g)
    {
      if (String.IsNullOrEmpty(g))
        return ("\"" + "\"");
      else
        return ("\"" + g + "\"");

    }

    MemoryStream getCsvstream(List<Dal.TableWorkOrder> dealsToAdd)
    {

      System.Text.StringBuilder sb = new System.Text.StringBuilder();
      System.Text.StringBuilder lineBuilder = new System.Text.StringBuilder();

      foreach (Dal.TableWorkOrder toAdd in dealsToAdd)
      {
        Bll.clsOrganizationRelation r = new MLY.Bll.clsOrganizationRelation(toAdd.CustomerId.Value, toAdd.ContractorId.Value);

        lineBuilder = new System.Text.StringBuilder();
        if (isClient)
          lineBuilder.Append(r.Data.ContarctorCode);
        lineBuilder.Append(',');
        lineBuilder.Append(formatStringToCsv(toAdd.ContractorCatalogueCode));
        lineBuilder.Append(',');
        lineBuilder.Append(formatStringToCsv(toAdd.ContractorWorkOrderNumber));
        lineBuilder.Append(',');
        lineBuilder.Append(formatStringToCsv(toAdd.ContractorLotNumber));
        lineBuilder.Append(',');
        if (!isClient)
          lineBuilder.Append(r.Data.CustomerCode);
        lineBuilder.Append(',');
        lineBuilder.Append(formatStringToCsv(toAdd.CustomerCatalougeCode));
        lineBuilder.Append(',');

        lineBuilder.Append(toAdd.CustomerPriority);
        lineBuilder.Append(',');
        lineBuilder.Append(formatStringToCsv(toAdd.CustomerWorkOrderNumber));
        lineBuilder.Append(',');
        lineBuilder.Append(toAdd.RequestedDelivaryDate.HasValue ? toAdd.RequestedDelivaryDate.Value.ToShortDateString() : "");
        lineBuilder.Append(',');
        lineBuilder.Append(toAdd.SendDate.HasValue ? toAdd.SendDate.Value.ToShortDateString() : "");
        lineBuilder.Append(',');
        lineBuilder.Append(toAdd.PlannedDelivaryDate.HasValue ? toAdd.PlannedDelivaryDate.Value.ToShortDateString() : "");
        lineBuilder.Append(',');
        lineBuilder.Append(toAdd.ActualDelivaryDate.HasValue ? toAdd.ActualDelivaryDate.Value.ToShortDateString() : "");
        lineBuilder.Append(',');
        lineBuilder.Append(formatStringToCsv(toAdd.ProductDescription));
        lineBuilder.Append(',');
        lineBuilder.Append(toAdd.Quantity);
        lineBuilder.Append(',');

        lineBuilder.Append(toAdd.SplitId);
        lineBuilder.Append(',');
        lineBuilder.Append(formatStringToCsv(toAdd.TextFieldA));
        lineBuilder.Append(',');
        lineBuilder.Append(formatStringToCsv(toAdd.TextFieldB));
        lineBuilder.Append(',');
        lineBuilder.Append(formatStringToCsv(toAdd.TextFieldC));
        lineBuilder.Append(',');
        lineBuilder.Append(toAdd.DateFieldA.HasValue ? toAdd.DateFieldA.Value.ToShortDateString() : "");
        lineBuilder.Append(',');
        lineBuilder.Append(toAdd.DateFieldB.HasValue ? toAdd.DateFieldB.Value.ToShortDateString() : "");
        lineBuilder.Append(',');
        lineBuilder.Append(formatStringToCsv(toAdd.Remarks));
        lineBuilder.Append(',');
        lineBuilder.Append(formatStringToCsv(toAdd.OrderNumber));

        sb.AppendLine(lineBuilder.ToString());
      }

      BinaryFormatter bf = new BinaryFormatter();
      MemoryStream retVal = new MemoryStream();
      bf.Serialize(retVal, sb.ToString());
      return retVal;
    }

    MemoryStream getXmlstream(List<Dal.TableWorkOrder> dealsToAdd)
    {
      XmlDocument xd = new XmlDocument();
      XmlElement root = xd.CreateElement("workorders");
      xd.AppendChild(root);
      foreach (Dal.TableWorkOrder toAdd in dealsToAdd)
      {
        Bll.clsOrganizationRelation r = new MLY.Bll.clsOrganizationRelation(toAdd.CustomerId.Value, toAdd.ContractorId.Value);

        XmlElement e1 = xd.CreateElement("wo");
        e1.AppendChild(getElement("ContractorCode", xd, r.Data.ContarctorCode));
        e1.AppendChild(getElement("ContractorCatalogueCode", xd, toAdd.CustomerCatalougeCode));
        e1.AppendChild(getElement("ContractorWorkOrderNumber", xd, toAdd.ContractorWorkOrderNumber));
        e1.AppendChild(getElement("ContractorLotNumber", xd, toAdd.ContractorLotNumber));
        e1.AppendChild(getElement("CustomerCode", xd, r.Data.CustomerCode));
        e1.AppendChild(getElement("CustomerCatalougeCode", xd, toAdd.CustomerCatalougeCode));
        e1.AppendChild(getElement("CustomerPriority", xd, toAdd.CustomerPriority));
        e1.AppendChild(getElement("CustomerWorkOrderNumber", xd, toAdd.CustomerWorkOrderNumber));
        e1.AppendChild(getElement("RequestedDelivaryDate", xd, toAdd.RequestedDelivaryDate.HasValue ? toAdd.RequestedDelivaryDate.Value.ToShortDateString() : ""));
        e1.AppendChild(getElement("SendDate", xd, toAdd.SendDate.HasValue ? toAdd.SendDate.Value.ToShortDateString() : ""));
        e1.AppendChild(getElement("PlannedDelivaryDate", xd, toAdd.PlannedDelivaryDate.HasValue ? toAdd.PlannedDelivaryDate.Value.ToShortDateString() : ""));
        e1.AppendChild(getElement("ActualDelivaryDate", xd, toAdd.ActualDelivaryDate.HasValue ? toAdd.ActualDelivaryDate.Value.ToShortDateString() : ""));
        e1.AppendChild(getElement("ProductDescription", xd, toAdd.ProductDescription));
        e1.AppendChild(getElement("Quantity", xd, toAdd.Quantity));
        e1.AppendChild(getElement("SplitId", xd, toAdd.SplitId));
        e1.AppendChild(getElement("TextFieldA", xd, toAdd.TextFieldA));
        e1.AppendChild(getElement("TextFieldB", xd, toAdd.TextFieldB));
        e1.AppendChild(getElement("TextFieldC", xd, toAdd.TextFieldC));
        e1.AppendChild(getElement("Remarks", xd, toAdd.Remarks));
        e1.AppendChild(getElement("OrderNumber", xd, toAdd.OrderNumber));
        root.AppendChild(e1);
      }
      BinaryFormatter bf = new BinaryFormatter();
      MemoryStream retVal = new MemoryStream();
      bf.Serialize(retVal, xd.InnerXml);

      return retVal;
    }

    protected void ContractorIdDdl_DataBound(object sender, EventArgs e)
    {
    }

    protected void btnOk_Click1(object sender, EventArgs e)
    {
      sendFile();
    }

  }
}

